package com.lcf.system.manager;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.system.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 用户
 * @author lcf
 */
@Component
public class SysUserManager {
    /**
     * 检查用户是否存在
     */
    public void checkExist(Long id, SysUser dto) {
        SysUser sysUser = Db.lambdaQuery(SysUser.class)
                .and(x -> x.eq(SysUser::getUsername, dto.getUsername())
                        .or().eq(StringUtils.isNotBlank(dto.getMobile()), SysUser::getMobile, dto.getMobile())
                        .or().eq(StringUtils.isNotBlank(dto.getEmail()), SysUser::getEmail, dto.getEmail()))
                .ne(id != null, SysUser::getId, id)
                .one();

        if (sysUser != null) {
            if (Objects.equals(sysUser.getUsername(), dto.getUsername())) {
                throw new SysException("用户名已存在!");
            }
            if (Objects.equals(sysUser.getMobile(), dto.getMobile())) {
                throw new SysException("手机号已存在!");
            }
            if (Objects.equals(sysUser.getEmail(), dto.getEmail())) {
                throw new SysException("邮箱已存在!");
            }
        }
    }

    /**
     * 检查id
     */
    public void checkId(long id) {
        SysUser sysUser = Db.lambdaQuery(SysUser.class).eq(SysUser::getId, id).one();
        if (sysUser == null) {
            throw new SysException("用户不存在");
        }
    }
}
